class Solution
{
public:
    bool validTicTacToe(vector<string> &board)
    {
        int xCount = 0, oCount = 0;
        for (auto &row : board)
        {
            for (char c : row)
            {
                if (c == 'X')
                {
                    ++xCount;
                }
                else if (c == 'O')
                {
                    ++oCount;
                }
            }
        }
        if (!(xCount == oCount || xCount == oCount + 1))
        {
            return false;
        }
        int xWin = 0, oWin = 0;
        for (int i = 0; i < 3; ++i)
        {
            if (board[i][0] == board[i][1] && board[i][1] == board[i][2])
            {
                if (board[i][0] == 'X')
                {
                    ++xWin;
                }
                else if (board[i][0] == 'O')
                {
                    ++oWin;
                }
            }
            if (board[0][i] == board[1][i] && board[1][i] == board[2][i])
            {
                if (board[0][i] == 'X')
                {
                    ++xWin;
                }
                else if (board[0][i] == 'O')
                {
                    ++oWin;
                }
            }
        }
        if (board[0][0] == board[1][1] && board[1][1] == board[2][2])
        {
            if (board[0][0] == 'X')
            {
                ++xWin;
            }
            else if (board[0][0] == 'O')
            {
                ++oWin;
            }
        }
        if (board[2][0] == board[1][1] && board[1][1] == board[0][2])
        {
            if (board[2][0] == 'X')
            {
                ++xWin;
            }
            else if (board[2][0] == 'O')
            {
                ++oWin;
            }
        }
        if (xWin && oWin)
        {
            return false;
        }
        if (xWin)
        {
            return xCount == oCount + 1;
        }
        if (oWin)
        {
            return xCount == oCount;
        }
        return true;
    }
};